package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetGroupChatList(param map[string]interface{}, order string, page, size int) ([]*models_main.GroupChat, error) {
	fName := "GetGroupChatList"
	o := make([]*models_main.GroupChat, 0)
	table := mysql.GetRTable(&models_main.GroupChat{})
	_, ok := param["status"]
	if !ok {
		param["status"] = models_main.GroupChatStatusNormal
	}
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetGroupChat(param map[string]interface{}) (*models_main.GroupChat, error) {
	fName := "GetGroupChat"
	o := &models_main.GroupChat{}
	table := mysql.GetRTable(&models_main.GroupChat{})
	_, ok := param["status"]
	if !ok {
		param["status"] = models_main.GroupChatStatusNormal
	}
	mysql.Condition(table, param, "", "id desc", 0, 0)
	err := table.Take(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return o, nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertGroupChatTx(session *gorm.DB, groupChat *models_main.GroupChat) error {
	fName := "InsertGroupChat"
	err := session.Create(groupChat).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateGroupChat(columns []string, groupChat *models_main.GroupChat) error {
	fName := "UpdateGroupChat"
	err := global.GetX().
		Model(groupChat).
		Select(columns).
		Updates(groupChat).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateGroupChatsUserNum(groupChatIds []int) error {
	fName := "UpdateGroupChatsUserNum"
	sql := `
UPDATE main.db_group_chat t1 
SET t1.user_num = (
	SELECT COUNT(1) FROM main.db_group_chat_user t2 WHERE t2.group_id = t1.id
)
WHERE t1.id in ?
`
	err := global.GetX().Exec(sql, groupChatIds).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
